import {baseurl} from './config.js'



import api from './api.js'
const dontHideLoading = []
const dontShoweLoading = [api.getAgreementContentByCargoType,api.newslist,api.navigation,api.waybilllist]
let timer = null


const baseRequest = (opts, data) => {
	let baseDefaultOpts = {
		url: baseurl + opts.url,
		// 请求接口地址
		data: data,
		// 传入请求参数
		method: opts.method,
		// 配置请求类型
		header: opts.method == 'POST' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		// 配置请求头
		dataType: 'json',
	}
	uni.showLoading({
		title: "正在加载.."
	})
	let promise = new Promise(function(resolve, reject) {
		
			uni.request(baseDefaultOpts).then((res) => {
					uni.hideLoading()
					let code = res.data.code;
					resolve(res);					
				}
			).catch((response) => {
					reject(response)
				}
			)
		
		
	})
	return promise
};

const dealRes = (opts,res,resolve, reject) => {
	if(res.data && res.data.code){
		let code = parseInt(res.data.code);
		
		switch (code) {
			case 200:
				if (dontHideLoading.indexOf(opts.url) === -1) {
					uni.hideLoading()
				}
				resolve(res);
				break;
			case 401:
				uni.hideLoading()
				uni.showToast({
					icon: 'none',
					title: res.data.message,
					duration: 1500
				});
				if(timer){
					clearTimeout(timer);
					timer = null
				}
				timer = setTimeout(() => {
					let page = getcurrentPage()
					uni.removeStorageSync('usertoken');
					// store.commit("wsClose",{code:1000,reason:'退出登录'})
					uni.reLaunch({
						url: '/pages/login/index?page='+page
					});
				}, 1500)
				break;
			default:
				if (dontHideLoading.indexOf(opts.url) === -1) {
					uni.hideLoading()
				}
				resolve(res);
		}
	}else{
		if (dontHideLoading.indexOf(opts.url) === -1) {
			uni.hideLoading()
		}
		resolve(res);
	}
}

const getcurrentPage = () => {
	let pageslist = getCurrentPages();
	let len = pageslist.length;
	let currentpage = pageslist[len-1];
	let currentpath = currentpage.$page ? currentpage.$page.fullPath : currentpage.route
	if(currentpath.indexOf("/login/index") > -1) currentpath = '';
	return encodeURIComponent(currentpath);
}

// token请求封装
const httpTokenRequest = (opts, data) => {	
	let token = uni.getStorageSync('token');
	if(!token){
		let page = getcurrentPage()
		uni.reLaunch({
			url: '/pages/login/index?page='+page
		});
	}
	
	let headers = Object.assign({},{
		"Accept": "application/json",
		'X-Requested-With': 'XMLHttpRequest',
		'Authorization': token
	})
	const method = opts.method ? opts.method.toUpperCase() : "GET";
		console.log('llllllll',opts.contentType)
	if(opts.contentType){
		headers["Content-Type"] = opts.contentType
	}else{
		headers["Content-Type"] = method === 'GET' ? "application/json; charset=UTF-8" : "application/x-www-form-urlencoded; charset=UTF-8"
	}
	//此token是登录成功后后台返回保存在storage中的
	let httpDefaultOpts = {
		url: baseurl + opts.url,
		data: data,
		method,
		header: headers,
		dataType: 'json',
	}
	console.log('？？',httpDefaultOpts)
	if (dontShoweLoading.indexOf(opts.url) === -1) {
		uni.showLoading({
			title: "正在加载.."
		})
	}
	// 不隐藏loading的URL
	let promise = new Promise(function(resolve, reject) {
		
			uni.request(httpDefaultOpts).then(
				(res) => {
					let r = res;
					dealRes(opts,r,resolve, reject)
				}
			).catch(
				(response) => {
					reject(response)
				}
			)
		
	})
	return promise
};



// 上传图片封装
const uploadFile = (obj) => {
	if (dontShoweLoading.indexOf(obj.url) === -1) {
		uni.showLoading({
			title: obj.toastText || "图片上传中.."
		})
	}
	let token = uni.getStorageSync('usertoken');
	let url = baseurl + obj.url; //服务器地址
	let filePath = obj.filePath; //要上传文件资源的路径。
	let formData = obj.formData || {};
	let success = obj.success;
	let name = obj.name || 'file'; //文件对应的 key 
	let method = obj.methods || 'POST'; //默认post请求
	
	// let promise = new Promise(function(resolve, reject) {
		
			try{
				uni.uploadFile({
						url: url,
						filePath: filePath,
						name: name,
						formData: formData,
						header: {
							'accessToken': token
						},
						success: function(res) {
							console.log("success ",res);
							const statusCode = res.statusCode;
							if(statusCode === 200){
								let data = JSON.parse(res.data);
								let code = data.code;
								let message = data.message;
								switch (code) {
									case 200:
										if (dontHideLoading.indexOf(obj.url) === -1) {
											uni.hideLoading()
										}
										success(data);
										break;
									case 401:
										uni.showToast({
											icon: 'none',
											title: "登录超时",
											duration: 1500
										});
										setTimeout(() => {
											uni.reLaunch({
												url: '/pages/login/index'
											});
										}, 1500)
										break;
									default:
										uni.showToast({
											title: message,
											duration: 2000,
											icon: "none"
										});
											
								}
							}else{
								const message = res.data;
								uni.showToast({
									title: message,
									duration: 4000,
									icon: "none"
								});
							}
						},
						fail: function(res) {
							let message = "接口请求失败"
							uni.showToast({
								title: res.errMsg,
								duration: 3000,
								icon: "none"
							});
						},
						complete: function(res) {
							
				
						},
					})
				
			}catch(e){
				console.log("upload img error ",e)
				uni.showToast({
					title: "上传超时，请稍后重试",
					duration: 3000,
					icon: "none"
				});
			}
		
		
	// })
	// return promise
	
	
}

export default {
	httpTokenRequest,
	uploadFile,
	baseRequest
};

